/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controller.Conexion;
import Controller.Producto;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author PEC
 */
public class ABMProducto extends javax.swing.JDialog {
    
    private Statement st = (Statement) Conexion.conectar();
    private ResultSet rs;
    private boolean validado;

    /**
     * Creates new form ABMProducto
     */
    public ABMProducto(java.awt.Frame parent, boolean modal, String tipoArt) {
        
        super(parent, modal);
        initComponents();
        llenaComboTalle(tipoArt);
        llenaComboColor();
    }
    
    public ABMProducto(java.awt.Frame parent, boolean modal, boolean update){
        super(parent, modal);
        initComponents();
        if(update){
            comboColor.setEnabled(false);
            comboTalle.setEnabled(false);
            txtCantidad.setEnabled(false);
            checkRemanente.setEnabled(false);
            btnEliminarArt.setEnabled(false);
            btnAgregaArt.setEnabled(false);
        }
        else{
            comboColor.setEnabled(false);
            comboTalle.setEnabled(false);
            txtDescripcion.setEnabled(false);
            txtPrecio.setEnabled(false);
            txtCantidad.setEnabled(false);
            checkRemanente.setEnabled(false);
            btnActualizaArt.setEnabled(false);
            btnAgregaArt.setEnabled(false);
        }
    }
    /**
     * Este metodo llena el dropDown con los valores obtenidos de la Base de Datos
     */
    private void llenaComboTalle(String articulo){
        comboTalle.removeAllItems();
        st = (Statement) Conexion.conectar();
        comboTalle.removeAllItems();
        int tipo = validarTipoArticulo(articulo);
        if(tipo != 0){
            try {
                rs = st.executeQuery("SELECT * FROM talle WHERE tipo like '" + tipo +"'");
                comboTalle.addItem("Seleccione Talle");
                while (rs.next()) {
                    comboTalle.addItem(rs.getString("talle"));
                }
                rs.close();
            } catch (Exception ex) {
                Logger.getLogger(FiltrarProductos.class.getName()).log(Level.SEVERE, null, ex);
            }   
        }
        else{
            comboTalle.setEnabled(false);
            comboColor.setEnabled(false);
        }
    }
    
    /**
     * Este metodo llena el dropDown con los valores obtenidos de la Base de Datos
     */
    private void llenaComboColor(){
        comboColor.removeAllItems();
        st = (Statement)Conexion.conectar();
        try{
            rs = st.executeQuery("SELECT * FROM color");
            comboColor.addItem("Seleccione Color");
            while (rs.next()) {
                comboColor.addItem(rs.getString("color"));
            }
            rs.close();
        }
        catch(Exception ex){
            Logger.getLogger(FiltrarProductos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /*
     * Este metodo determina el tipo de articulo seleccionado para determinar el
     * tipo de talle que se usara
     */
    private int validarTipoArticulo(String articulo){
        int tipoArt = 0;
        if(articulo.equals("Remeras")||
           articulo.equals("Buzos")||
           articulo.equals("Camisas")||
           articulo.equals("Bikinis")){
            tipoArt = 1;
        }
        else if(articulo.equals("Pantalones")||
                articulo.equals("Bermudas")||
                articulo.equals("Mallas")){
            tipoArt = 2;
        }
        else if(articulo.equals("Zapatillas")){
            tipoArt = 3;
        }
        return tipoArt;
    }  
    
    /*
     * Este metodo realiza validaciones para determinar que los datos ingresados
     * son correctos 
     */
    private boolean validarCampos(){
        //Valida codigo de barras
        if((txtCodigo.getText().isEmpty())){
           validado = false;
        }
        //Valida que la descripcion no este vacia
        else if((txtDescripcion.getText().isEmpty())){
           validado = false;
        }
        //Valida que el talle sea correcto
        else if((comboTalle.getSelectedItem().equals("Seleccione Talle"))){
           validado = false;
        }
        //Valida que el color sea correcto
        else if((comboColor.getSelectedItem().equals("Seleccione Color"))){
           validado = false;
        }
        else if((txtPrecio.getText().isEmpty())){
           validado = false;
        }
        else if((txtCantidad.getText().isEmpty())){
           validado = false;
        }
        else if((txtRemanente.getText().isEmpty()) && checkRemanente.isSelected()){
            validado = false;
        }
        else{
             validado = true;
        }
        return validado;
    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtCodigo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        comboTalle = new javax.swing.JComboBox();
        comboColor = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        checkRemanente = new javax.swing.JRadioButton();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtRemanente = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnAgregaArt = new javax.swing.JButton();
        btnActualizaArt = new javax.swing.JButton();
        btnEliminarArt = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Código artículo");

        jLabel4.setText("Descripción");

        jLabel5.setText("Talle");

        jLabel6.setText("Color");

        jLabel7.setText("Precio");

        checkRemanente.setText("(Marcar si es de la temporada anterior)");

        jLabel8.setText("¿Remanente?");

        jLabel9.setText("Cantidad");

        jLabel3.setText("Cantidad");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(txtRemanente, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(checkRemanente))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(comboTalle, 0, 237, Short.MAX_VALUE)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtDescripcion, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(comboColor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtPrecio)
                                .addComponent(txtCantidad)))))
                .addGap(40, 40, 40))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboTalle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkRemanente)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtRemanente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Administrar artículos");

        btnAgregaArt.setText("Agregar");
        btnAgregaArt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregaArtActionPerformed(evt);
            }
        });

        btnActualizaArt.setText("Actualizar");
        btnActualizaArt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizaArtActionPerformed(evt);
            }
        });

        btnEliminarArt.setText("Eliminar");
        btnEliminarArt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarArtActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAgregaArt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnActualizaArt, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(btnEliminarArt, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEliminarArt)
                    .addComponent(btnActualizaArt)
                    .addComponent(btnAgregaArt))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregaArtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregaArtActionPerformed
        /*Valida si el producto existe o no. Si la condicion es verdadera agrega una variante del 
         * articulo, si es falsa, agrega uno nuevo
         */
        validado = validarCampos();
        if(!validado){
            JOptionPane.showMessageDialog(null, "Revise los datos ingresados");
        }else{
            String talle = (String)comboTalle.getSelectedItem();
            String color = (String)comboColor.getSelectedItem();
            
            if(Controller.Producto.existeArticulo(st, txtCodigo.getText())){
                Controller.Producto.insertaVarianteProducto(txtCodigo.getText(), txtDescripcion.getText(), 
                                                            color, talle, txtPrecio.getText(),
                                                            txtCantidad.getText(), checkRemanente.isSelected(), txtRemanente.getText(), st);
                JOptionPane.showMessageDialog(null, "Artículo agregado");
            }
            else{
                Controller.Producto.insertaNuevoProducto(txtCodigo.getText(), txtDescripcion.getText(), 
                                                        color, talle, txtPrecio.getText(),
                                                        txtCantidad.getText(), checkRemanente.isSelected(), txtRemanente.getText(), st);
                JOptionPane.showMessageDialog(null, "Artículo agregado");
            }
        }
    }//GEN-LAST:event_btnAgregaArtActionPerformed

    private void btnEliminarArtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarArtActionPerformed
        /*
         * Si existe el articulo, lo elimina de la Base de Datos, sino avisa que dicho articulo no existe
         */
        String codigo = txtCodigo.getText();
        
        if(Controller.Producto.existeArticulo(st, codigo)){    
            Controller.Producto.eliminaArticulo(codigo);
        }
        else{
            JOptionPane.showMessageDialog(null, "No existe el artículo a eliminar");
        }        
    }//GEN-LAST:event_btnEliminarArtActionPerformed

    private void btnActualizaArtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizaArtActionPerformed
        String codigo = txtCodigo.getText();
        String descripcion = txtDescripcion.getText();
        String precio = txtPrecio.getText();
        
        if(Controller.Producto.existeArticulo(st, codigo)){    
            Controller.Producto.actualizaArticulo(st, codigo, descripcion, precio);
        }
        else{
            JOptionPane.showMessageDialog(null, "No existe el artículo a actualizar");
        }
    }//GEN-LAST:event_btnActualizaArtActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ABMProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ABMProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ABMProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ABMProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                String tipoArt = "a";
                ABMProducto dialog = new ABMProducto(new javax.swing.JFrame(), true, tipoArt);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActualizaArt;
    private javax.swing.JButton btnAgregaArt;
    private javax.swing.JButton btnEliminarArt;
    private javax.swing.JRadioButton checkRemanente;
    private javax.swing.JComboBox comboColor;
    private javax.swing.JComboBox comboTalle;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtDescripcion;
    private javax.swing.JTextField txtPrecio;
    private javax.swing.JTextField txtRemanente;
    // End of variables declaration//GEN-END:variables
}
